/******************************************************************************
	This file is a part of the Snapshot Bioinformatics Project

	Copyright (C) 2012-2013 Jarom Schow

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/

#include "TaxonTree.h"

#include <QtCore/QMap>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>

using namespace Bio;

const int c_rootTaxonId = 1;

// taxon table:
const QString c_taxon = "taxon";
const QString c_taxonId = "taxon_id";
const QString c_ncbiTaxonId = "ncbi_taxon_id";
const QString c_parentTaxonId = "parent_taxon_id";
const QString c_nodeRank = "node_rank";
const QString c_geneticCode = "genetic_code";
const QString c_mitoGeneticCode = "mito_genetic_code";
const QString c_leftValue = "left_value";
const QString c_rightValue = "right_value";

// taxon_name table:
const QString c_taxonName = "taxon_name";
//const QString c_taxonId = "taxon_id";
const QString c_name = "name";
const QString c_nameClass = "nameClass";

struct TaxonTree::Data
{
	QSqlDatabase		m_db;
	QMap<int, Taxon*>	m_taxonMap;
};

/**
**/
TaxonTree::TaxonTree( QSqlDatabase &db ) : m_data( new Data )
{
	m_data->m_db = db;
}

/**
**/
TaxonTree::~TaxonTree()
{
	delete m_data;
	m_data = NULL;
}

/**
**/
Taxon* TaxonTree::getRoot()
{
	return getTaxonById( c_rootTaxonId );
}

/**
**/
Taxon* TaxonTree::findTaxonByName( const QString &name )
{
	return NULL;
}

/**
**/
Taxon* TaxonTree::getTaxonById( int id )
{
	if( m_data->m_taxonMap.contains( id ) )
		return m_data->m_taxonMap[id];

	if( loadTaxon( id ) )
		return m_data->m_taxonMap[id];

	return NULL;
}

/**
**/
Taxon* TaxonTree::getTaxonByNcbiId( int ncbiId )
{
	return NULL;
}

/**
**/
bool TaxonTree::loadTaxon( int taxonId )
{
	if( !m_data->m_db.isOpen() )
		return false;

	QString		queryStr = QString( "SELECT * FROM %1 WHERE %2=%3;" ).arg( c_taxon ).arg( c_taxonId ).arg( taxonId );
	QSqlQuery	query = m_data->m_db.exec( queryStr );

	return true;
}
